﻿using Ldt.AnalysisRuleInfoUnit.Core.InterfaceHandle;
using LdtJudge.DataEngine.CallInterface.CommHelp;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Data;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel.CommonManageModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using static Ldt.DataEngine.LogHandle.LogHandle;

namespace Ldt.DataEngine.RuleAssemble
{
    public class RuleParseClass
    {

        /// <summary>
        /// 调用规则对象
        /// </summary>
        [ThreadStatic]
        private static InterfaceRuleInfoUnit _Ruleobj;



        /// <summary>
        /// 返回规则调用对象
        /// </summary>
        private static InterfaceRuleInfoUnit Ruleobj
        {
            get
            {

                _Ruleobj = _Ruleobj ?? new RuleInfoUnitInterface();
                //_Ruleobj.Connectionstring = connection;CauseDistinguish
                _Ruleobj.freeSql = FreeSQLHelp.GetFreeSQL("LdtCommonManage");
                _Ruleobj.TextClassificationConnectionstring = ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("CauseDistinguish");
                //var list=  _Ruleobj.freeSql.Select<RuleInfoUnit>().First();
                _Ruleobj.MQConnectionstring = ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("ArtificialIntelligence");
                _Ruleobj.RuleTimeOut = ConfigRetrieval.GetConfigRetrieval.ConfigManagerHandle.AnalysisRuleTimeSpan;
                //_Ruleobj.IsBufferRegex = true;
                return _Ruleobj;

            }

        }


        /// <summary>
        /// 根据规则编号获取规则需要的参数
        /// </summary>
        /// <param name="RuleCode">规则编号</param>
        /// <returns></returns>
        public static List<RiuParameterList> GetConfigList(string RuleCode)
        {
            var parameter = JsonConvert.DeserializeObject<RiuParameterList[]>(Ruleobj.GetRiu_ParameterList(RuleCode)).ToList();
            return parameter;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="RuleCode"></param>
        /// <param name="originalText"></param>
        /// <param name="RuleParameter"></param>
        /// <param name="times"></param>
        /// <returns></returns>
        public static IList<string> GetParseList(string RuleCode, string originalText, string RuleParameter = "", double times = 0)
        {
            try
            {
                IList<string> listvalue = ExtractList(RuleCode, originalText, RuleParameter);
                return listvalue;
            }
            catch (Exception ex)
            {

                throw;
            }
        }
        /// <summary>
        /// 进行数据处理
        /// </summary>
        /// <param name="RuleCode"></param>
        /// <param name="originalTextList"></param>
        /// <param name="RuleParameter"></param>
        /// <param name="times"></param>
        /// <returns></returns>
        public static Dictionary<string, List<string>> GetParseDicList(string RuleCode, List<string> originalTextList, string RuleParameter = "", double times = 0)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            Dictionary<string, List<string>> listvalue = new Dictionary<string, List<string>>();
            try
            {
                originalTextList[0] = get_uft8(originalTextList[0].Replace("\r", "\r"));
                listvalue = RegularList(originalTextList, RuleCode, RuleParameter);
                sw.Stop();
                TimeSpan timeSpan = sw.Elapsed;
                times = timeSpan.TotalMilliseconds;
            }
            catch (Exception ex)
            {
                originalTextList[0] = get_uft8(originalTextList[0].Replace("\r", ""));
                listvalue = RegularList(originalTextList, RuleCode, RuleParameter);
                sw.Stop();
                TimeSpan timeSpan = sw.Elapsed;
                times = timeSpan.TotalMilliseconds;
                if (listvalue.Count == 0)
                {
                    throw new Exception(ex.Message);
                }
            }

            return listvalue;
        }

        public static string get_uft8(string unicodeString)
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            Byte[] encodedBytes = utf8.GetBytes(unicodeString);
            String decodedString = utf8.GetString(encodedBytes);
            return decodedString;
        }
        /// <summary>
        /// 返回多个CODE信息
        /// </summary>
        /// <param name="RuleCode"></param>
        /// <param name="originalTextList"></param>
        /// <param name="code"></param>
        /// <param name="RuleParameter"></param>
        /// <returns></returns>
        public static List<string> GetParseRegCodeList(string InfoCode, List<string> originalTextList, string RuleParameter = "")
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            LogWirt(true, InfoCode, JsonConvert.SerializeObject(originalTextList), RuleParameter, "", 0);

            List<string> reList = new List<string>();
            Dictionary<string, List<string>> re = new Dictionary<string, List<string>>();
            re = RegularList(originalTextList, "", RuleParameter, InfoCode);
            if (re.ContainsKey("reg"))
            {
                reList = re["reg"];
            }

            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            double times = timeSpan.TotalMilliseconds;
            LogWirt(false, InfoCode, JsonConvert.SerializeObject(originalTextList), RuleParameter, "", times);
            return reList;
        }

        /// <summary>
        /// 获取正则结果
        /// </summary>
        /// <param name="InfoCode">正则编号</param>
        /// <param name="originalText">原文</param>
        /// <param name="RuleParameter">参数</param>
        /// <returns></returns>
        public static List<string> GetParseRegCodeList(string InfoCode, string originalText, string RuleParameter = "")
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            LogWirCause(true, InfoCode, originalText, RuleParameter, "", 0);
            LogWirt(true, InfoCode, originalText, RuleParameter, "", 0);
            List<string> reList = new List<string>();
            List<string> originalList = new List<string>();
            originalList.Add(originalText);
            Dictionary<string, List<string>> re = new Dictionary<string, List<string>>();
            re = RegularList(originalList, "", RuleParameter, InfoCode);
            if (re.ContainsKey("reg"))
            {
                reList = re["reg"];
            }
            else if (re.ContainsKey("Ai"))
            {
                reList = re["Ai"];
            }

            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            double times = timeSpan.TotalMilliseconds;
            LogWirCause(false, InfoCode, originalText, RuleParameter, "", times);
            LogWirt(false, InfoCode, originalText, RuleParameter, "", times);
            return reList;
        }

        /// <summary>
        /// 根据规则主键ID返回匹配的值的集合带分析过程
        /// </summary>
        /// <param name="originalText">原文集合</param>
        /// <param name="riu_id">规则主键ID</param>
        /// <param name="Parameter">参数</param>
        /// <param name="ResultAnalysis">分析过程数据</param>
        /// <returns>返回结果</returns>
        public static Dictionary<string, List<string>> Dic_GetExtractListAndAnalyticalProcess(List<string> originalText, string riu_id, string Parameter, out string ResultAnalysis)
        {
            return Ruleobj.Dic_GetExtractListAndAnalyticalProcess(originalText, riu_id, Parameter, out ResultAnalysis);
        }


        /// <summary>
        /// 获取正则结果及正则定位
        /// </summary>
        /// <param name="InfoCode">正则编号</param>
        /// <param name="originalText">原文</param>
        /// <param name="RuleParameter">参数</param>
        /// <returns></returns>
        public static Dictionary<string, List<string>> GetParseRegCodeListNew(string InfoCode, string originalText, string RuleParameter, out string rzContent)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            rzContent = string.Empty;
            LogWirCause(true, InfoCode, originalText, RuleParameter, "", 0);
            LogWirt(true, InfoCode, originalText, RuleParameter, "", 0);
            List<string> originalList = new List<string>();
            originalList.Add(originalText);
            Dictionary<string, List<string>> re = new Dictionary<string, List<string>>();
            try
            {
                re = RegularList(originalList, "", RuleParameter, InfoCode);
            }
            catch (RegexMatchTimeoutException)
            {

                rzContent = $"正则超时为【{InfoCode}】原文：{originalText}";
            }
            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            double times = timeSpan.TotalMilliseconds;
            if (sw.ElapsedMilliseconds > 3000)
            {
                string regParam = !string.IsNullOrWhiteSpace(RuleParameter) ? $"正则条件：{RuleParameter}," : string.Empty;
                string content = $"正则编号为【{InfoCode}】的正则执行时长{sw.ElapsedMilliseconds}毫秒,{regParam}原文：{originalText}";
                rzContent = rzContent+ content;
                //WriteLog("分析总时长" + swtext.ElapsedMilliseconds.ToString("0.00") + ",正则编号:" + regcode + "原文：" + text + "正则条件:" + tj, "\\log\\log.txt", false);
            }
            LogWirCause(false, InfoCode, originalText, RuleParameter, "", times);
            LogWirt(false, InfoCode, originalText, RuleParameter, "", times);
            return re;
        }

        /// <summary>
        /// 获取正则结果唯一值
        /// </summary>
        /// <param name="InfoCode">正则编号</param>
        /// <param name="originalText">原文</param>
        /// <param name="RuleParameter">参数</param>
        /// <returns></returns>
        public static string GetParseRegCodeValue(string InfoCode, string originalText, string RuleParameter = "")
        {

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            LogWirt(true, InfoCode, originalText, RuleParameter, "", 0);

            List<string> reList = new List<string>();
            List<string> originalList = new List<string>();
            string value = "";
            originalList.Add(originalText);
            Dictionary<string, List<string>> re = new Dictionary<string, List<string>>();
            re = RegularList(originalList, "", RuleParameter, InfoCode);
            if (re.ContainsKey("reg"))
            {
                reList = re["reg"];
            }
            if (reList.Count > 0)
            {
                value = reList[0];
            }

            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            double times = timeSpan.TotalMilliseconds;
            LogWirt(false, InfoCode, originalText, RuleParameter, "", times);
            return value;
        }

        /// <summary>
        /// 获取正则结果唯一值
        /// </summary>
        /// <param name="InfoCode">正则编号</param>
        /// <param name="originalText">多个原文</param>
        /// <returns></returns>
        public static List<string> GetParseRegCodeValueManyOrg(string infoCode, List<string> originalText)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            LogWirt(true, infoCode, string.Join(",", originalText), "", "", 0);
            SqlCmmCommon sqlCmm = new SqlCmmCommon("LdtCommonManage");
            List<RuleInfoUnit> dt = sqlCmm.GetRiuIDbyRiuCode(infoCode);
            string riuID = dt[0].RIU_ID.ToString();
            List<string> reList = new List<string>();//"MSGetPartiesParagraphClause"
            Dictionary<string, List<string>> re = new Dictionary<string, List<string>>();
            re = RegularList(originalText, riuID, "");
            if (re.ContainsKey("reg"))
            {
                reList = re["reg"];
            }
            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            double times = timeSpan.TotalMilliseconds;
            LogWirt(false, infoCode, string.Join(",", originalText), "", "", times);
            return reList;
        }

        /// <summary>
        /// 根据CC_ID返回RIU_ID
        /// </summary>
        /// <param name="cc_id">CC_ID</param>
        /// <returns></returns>
        public static string GetRIU_ID(string cc_id)
        {
            SqlCmmCommon sqlCmm = new SqlCmmCommon("LdtCommonManage");
            List<RuleInfoUnit> dt = sqlCmm.GetRiuIDbyRiuCode(cc_id);
            string riuID = dt[0].RIU_ID.ToString();
            return riuID;
        }
        /// <summary>
        /// 返回正则语句
        /// </summary>
        /// <param name="RuleCode">正则编号</param>
        /// <returns></returns>
        /// 
        public static List<string> GerParseReg(string RuleCode)
        {
            List<string> listValue = new List<string>();
            listValue = Ruleobj.GetRegexsByRiu_id(RuleCode).ToList();
            return listValue;
        }


        /// <summary>
        /// 根据原文内容，和xml内容进行匹配是否能够匹配上
        /// </summary>
        /// <param name="originalText">原文内容</param>
        /// <param name="XMLText">xml内容</param>
        /// <returns></returns>
        public static bool IsMatchKeyWordXML(string originalText, string XMLText)
        {
            bool result = true;
            XmlDocument document = new XmlDocument();
            document.LoadXml(XMLText);
            XmlNodeList listinclude = document.GetElementsByTagName("include");
            XmlNodeList listexclude = document.GetElementsByTagName("exclude");

            bool MatchOneXML(string mark, string OneXML, string originalTexttemp)
            {
                if (mark == "+")//包含
                {
                    bool ismatch = Regex.IsMatch(originalTexttemp, OneXML.Replace(',', '|').Replace('，', '|'));
                    if (ismatch)
                    {
                        return true;
                    }
                }
                else //排除
                {
                    bool ismatch = Regex.IsMatch(originalTexttemp, OneXML.Replace(',', '|').Replace('，', '|'));
                    if (ismatch)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                return false;
            }

            foreach (XmlNode node in listinclude)
            {
                result = result && MatchOneXML("+", node.InnerText, originalText);
            }
            foreach (XmlNode node in listexclude)
            {
                result = result && MatchOneXML("-", node.InnerText, originalText);
            }
            return result;
        }

        /// <summary>
        /// 正则编码转数据库中的规则ID
        /// </summary>
        /// <param name="regCode"></param>
        /// <returns></returns>
        public static string RegCodeToRIUID(string regCode)
        {
            return null;
        }

        [ThreadStatic]
        private static int _IsExtEnd;
        public static int IsExtEnd
        {
            get
            {
                if (_IsExtEnd == 0)
                {
                    _IsExtEnd = -1;
                }
                return _IsExtEnd;
            }
            set
            {
                _IsExtEnd = value;
            }
        }
        /// <summary>
        /// 日志打印
        /// </summary>
        /// <param name="isStart">开始还是结束</param>
        /// <param name="infoCode">The information code.</param>
        /// <param name="originalText">The original text.</param>
        /// <param name="regParameter">The reg parameter.</param>
        /// <param name="matchValue">The match value.</param>
        /// <param name="exttime">执行时间.</param>
        private static void LogWirt(bool isStart, string infoCode, string originalText, string regParameter, object matchValue, double exttime)
        {

            if (isStart)
            {
                //if (IsExtEnd != -1 && IsExtEnd == 1)
                //{ //上一次执行有问题
                //    GetInitLogHandle.LogWrite(LogHType.Debug, ">>>>>>>>>>>>>>>>>>>>>>Error>>>>>>>>>>>>>>>>>>>");
                //}
                ////开始执行正则
                //GetInitLogHandle.LogWrite(LogHType.Debug, "--------------------------------------开始------------------------------------");
                ////原文 
                //GetInitLogHandle.LogWrite(LogHType.Debug, "RegexMessage,当前原文为:" + originalText);

                ////参数 
                //GetInitLogHandle.LogWrite(LogHType.Debug, "RegexMessage, 参数为：" + regParameter);
                ////正则编号 
                //GetInitLogHandle.LogWrite(LogHType.Debug, "RegexMessage,正则编号：" + infoCode);

                //IsExtEnd = 1;
            }
            else
            {
                ////执行时间 
                //GetInitLogHandle.LogWrite(LogHType.Debug, "RegexMessage,执行时间为：" + exttime);
                ////匹配值 
                //GetInitLogHandle.LogWrite(LogHType.Debug, "RegexMessage, 匹配值为：" + LdtJudge.DataEngine.CallInterface.ConfigManager.ConfigManagerHandle.ReturnJsonString(matchValue));

                //GetInitLogHandle.LogWrite(LogHType.Debug, "--------------------------------------【结束】------------------------------------");

                //IsExtEnd = 0;
            }

        }

        /// <summary>
        /// 日志打印
        /// </summary>
        /// <param name="isStart">开始还是结束</param>
        /// <param name="infoCode">The information code.</param>
        /// <param name="originalText">The original text.</param>
        /// <param name="regParameter">The reg parameter.</param>
        /// <param name="matchValue">The match value.</param>
        /// <param name="exttime">执行时间.</param>
        private static void LogWirCause(bool isStart, string infoCode, string originalText, string regParameter, object matchValue, double exttime)
        {

            if (isStart)
            {
                //if (IsExtEnd != -1 && IsExtEnd == 1)
                //{ //上一次执行有问题
                //    GetInitLogHandle.LogWrite(LogHType.Debug, ">>>>>>>>>>>>>>>>>>>>>>Error>>>>>>>>>>>>>>>>>>>");
                //}
                ////开始执行正则
                //GetInitLogHandle.LogWrite(LogHType.Debug, "--------------------------------------开始------------------------------------");
                ////原文 
                //GetInitLogHandle.LogWrite(LogHType.Debug, "RegexMessage,当前原文为:" + originalText);
                ////参数 
                //GetInitLogHandle.LogWrite(LogHType.Debug, "RegexMessage, 参数为：" + regParameter);
                ////正则编号 
                //GetInitLogHandle.LogWrite(LogHType.Debug, "RegexMessage,正则编号：" + infoCode);

                IsExtEnd = 1;
            }
            else
            {
                ////执行时间 
                //GetInitLogHandle.LogWrite(LogHType.Debug, "RegexMessage,执行时间为：" + exttime);
                ////匹配值 
                //GetInitLogHandle.LogWrite(LogHType.Debug, "RegexMessage, 匹配值为：" + LdtJudge.DataEngine.CallInterface.ConfigManager.ConfigManagerHandle.ReturnJsonString(matchValue));

                //GetInitLogHandle.LogWrite(LogHType.Debug, "--------------------------------------【结束】------------------------------------");

                IsExtEnd = 0;
            }

            //if (isStart)
            //{
            //    if (IsExtEnd != -1 && IsExtEnd == 1)
            //    { //上一次执行有问题
            //        GetInitLogHandle.LogWrite(LogHType.Warn, ">>>>>>>>>>>>>>>>>>>>>>Error>>>>>>>>>>>>>>>>>>>");
            //    }
            //    //开始执行正则
            //    GetInitLogHandle.LogWrite(LogHType.Warn, "--------------------------------------开始------------------------------------");
            //    //原文 
            //    GetInitLogHandle.LogWrite(LogHType.Warn, "RegexMessage,当前原文为:" + originalText);
            //    //参数 
            //    GetInitLogHandle.LogWrite(LogHType.Warn, "RegexMessage, 参数为：" + regParameter);
            //    //正则编号 
            //    GetInitLogHandle.LogWrite(LogHType.Warn, "RegexMessage,正则编号：" + infoCode);

            //    IsExtEnd = 1;
            //}
            //else
            //{
            //    //执行时间 
            //    GetInitLogHandle.LogWrite(LogHType.Warn, "RegexMessage,执行时间为：" + exttime);
            //    //匹配值 
            //    GetInitLogHandle.LogWrite(LogHType.Warn, "RegexMessage, 匹配值为：" + LdtJudge.DataEngine.CallInterface.ConfigManager.ConfigManagerHandle.ReturnJsonString(matchValue));

            //    GetInitLogHandle.LogWrite(LogHType.Warn, "--------------------------------------【结束】------------------------------------");

            //    IsExtEnd = 0;
            //}


        }
        /// <summary>
        /// 获取正则信息
        /// </summary>
        public static string GetRegString(string infoCode)
        {
            string value = "";
            SqlCmmCommon sqlCmm = new SqlCmmCommon("LdtCommonManage");
            List<string> dt = sqlCmm.GetRiuCodebyReg(infoCode);
            if (dt.Count > 0)
            {
                value = dt[0];
            }
            return value;
        }
        /// <summary>
        /// 根据正则编号获取结果
        /// </summary>
        /// <param name="infoCode">正则编号</param>
        /// <param name="originalText">原文</param>
        /// <returns></returns>
        public static string GetParseValue(string infoCode, string originalText)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            LogWirt(true, infoCode, originalText, "", "", 0);

            List<string> originalTextList = new List<string>();
            originalTextList.Add(originalText);
            SqlCmmCommon sqlCmm = new SqlCmmCommon("LdtCommonManage");
            List<RuleInfoUnit> dt = sqlCmm.GetRiuIDbyRiuCode(infoCode);
            Dictionary<string, List<string>> re = new Dictionary<string, List<string>>();
            List<string> reList = new List<string>();
            string riuID = string.Empty;
            if (dt.Count == 0)
            {
                re = RegularList(originalTextList, "", "", infoCode);
            }
            else
            {
                riuID = dt[0].RIU_ID.ToString();
                //"MSGetPartiesParagraphClause"
                re = RegularList(originalTextList, riuID, "");
            }
            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            double times = timeSpan.TotalMilliseconds;
            LogWirt(false, infoCode, originalText, "", "", times);
            //WriteLog(originalText, "正则编号：EIID:" + infoCode+"riuID:"+ riuID,  times, "", true);

            if (re.ContainsKey("reg"))
            {
                reList = re["reg"];
            }
            if (reList.Count > 0)
            {
                return reList[0];
            }
            else
            {
                return "";
            }

        }

        /// <summary>
        /// 通过规则编号获取字典数据
        /// </summary>
        public static Dictionary<string, List<string>> GetParseValueDic(string infoCode, string originalText)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            LogWirt(true, infoCode, originalText, "", "", 0);

            List<string> originalTextList = new List<string>();
            originalTextList.Add(originalText);
            SqlCmmCommon sqlCmm = new SqlCmmCommon("LdtCommonManage");
            List<RuleInfoUnit> dt = sqlCmm.GetRiuIDbyRiuCode(infoCode);
            Dictionary<string, List<string>> re = new Dictionary<string, List<string>>();
            List<string> reList = new List<string>();
            if (dt.Count == 0)
            {
                re = RegularList(originalTextList, "", "", infoCode);
            }
            else
            {
                string riuID = dt[0].RIU_ID.ToString();
                //"MSGetPartiesParagraphClause"
                re = RegularList(originalTextList, riuID, "");
            }
            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            double times = timeSpan.TotalMilliseconds;
            LogWirt(false, infoCode, originalText, "", "", times);
            return re;
        }

        /// <summary>
        /// 查看是否匹配
        /// </summary>
        /// <param name="infoCode"></param>
        /// <param name="originalText"></param>
        /// <returns></returns>
        public static bool IsMatchs(string infoCode, string originalText)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            LogWirCause(true, infoCode, originalText, "", "", 0);
            SqlCmmCommon sqlCmm = new SqlCmmCommon("LdtCommonManage");
            List<RuleInfoUnit> dt = sqlCmm.GetRiuIDbyRiuCode(infoCode);
            if (dt.Count > 0)
            {
                List<string> originalTextList = new List<string>();
                originalTextList.Add(originalText);
                List<string> reList = new List<string>();
                Dictionary<string, List<string>> re = new Dictionary<string, List<string>>();
                re = RegularList(originalTextList, dt[0].RIU_ID.ToString());
                sw.Stop();
                TimeSpan timeSpan = sw.Elapsed;
                double times = timeSpan.TotalMilliseconds;
                LogWirCause(false, infoCode, originalText, "", "", times);
                if (re.ContainsKey("match"))
                {
                    reList = re["match"];
                    if (reList[0] == "1")
                    {

                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            return false;
        }

        public static bool IsMatchsp(string infoCode, string originalText)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            LogWirCause(true, infoCode, originalText, "", "", 0);
            SqlCmmCommon sqlCmm = new SqlCmmCommon("LdtCommonManage");
            List<RuleInfoUnit> dt = sqlCmm.GetRiuIDbyRiuCode(infoCode);
            if (dt.Count > 0)
            {
                List<string> originalTextList = new List<string>();
                originalTextList.Add(originalText);
                List<string> reList = new List<string>();
                Dictionary<string, List<string>> re = new Dictionary<string, List<string>>();
                re = RegularList(originalTextList, dt[0].RIU_ID.ToString());
                sw.Stop();
                TimeSpan timeSpan = sw.Elapsed;
                double times = timeSpan.TotalMilliseconds;
                LogWirCause(false, infoCode, originalText, "", "", times);
                if (re.ContainsKey("reg"))
                {

                    if (re["reg"].Count > 0)
                    {

                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            return false;
        }

        public static bool IsMatch(string infoCode, string originalText)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            LogWirCause(true, infoCode, originalText, "", "", 0);
            List<string> originalTextList = new List<string>();
            originalTextList.Add(originalText);
            List<string> reList = new List<string>();
            Dictionary<string, List<string>> re = new Dictionary<string, List<string>>();
            re = RegularList(originalTextList, infoCode);
            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            double times = timeSpan.TotalMilliseconds;
            LogWirCause(false, infoCode, originalText, "", "", times);

            if (re.ContainsKey("match"))
            {
                reList = re["match"];
                if (reList[0] == "1")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }

        }
        /// <summary>
        /// 通过正则获取
        /// </summary>
        /// <param name="infoCode">正则编号</param>
        /// <returns></returns>
        public static string GerRegValue(string infoCode)
        {
            IList<string> listvalue = Ruleobj.GetRegularList(infoCode);
            string value = "";
            if (listvalue.Count > 0)
            {
                return listvalue[0];
            }
            return value;
        }

        /// <summary>
        /// 执行正则模块超时时间设定为25秒
        /// </summary>
        /// <param name="originalText">原文</param>
        /// <param name="riu_id">正则ID</param>
        /// <param name="Parameter">参数</param>
        /// <returns></returns>
        public static Dictionary<string, List<string>> RegularList(List<string> originalText, string riu_id, string Parameter)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();


            if (!string.IsNullOrEmpty(Parameter))
            {
                Parameter = Parameter.Replace("*", @"\*");
            }
            Dictionary<string, List<string>> keyValues = new Dictionary<string, List<string>>();

            IList<string> listvalue = Ruleobj.GetRegexsByRiu_id(riu_id);
            keyValues = Ruleobj.Dic_GetExtractList(originalText, riu_id, Parameter);
            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            double times = timeSpan.TotalMilliseconds;
            WriteLog(string.Join(",", originalText), riu_id, times, Parameter, false);
            return keyValues;
        }
        /// <summary>
        /// 执行正则模块超时时间设定为25秒
        /// </summary>
        /// <param name="originalText">原文</param>
        /// <param name="riu_id">正则ID</param>
        /// <param name="Parameter">参数</param>
        /// <param name="Code"></param>
        /// <returns></returns>
        public static Dictionary<string, List<string>> RegularList(List<string> originalText, string riu_id, string Parameter, string Code)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            if (!string.IsNullOrEmpty(Parameter))
            {
                Parameter = Parameter.Replace("*", @"\*");
            }

            Dictionary<string, List<string>> keyValues = new Dictionary<string, List<string>>();
            //new System.Threading.Tasks.TaskFactory().StartNew(() =>
            //{
            keyValues = Ruleobj.Dic_GetExtractList(originalText, riu_id, Parameter, Code);
            //}).Wait(25000);

            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            double times = timeSpan.TotalMilliseconds;
            if (string.IsNullOrEmpty(riu_id))
            {
                riu_id = Code;
            }
            WriteLog(string.Join(",", originalText), riu_id, times, Parameter, false);


            return keyValues;
        }

        /// <summary>
        /// 执行正则模块超时时间设定为25秒
        /// </summary>
        /// <param name="originalText">原文</param>
        /// <param name="riu_id">正则ID</param>
        /// <returns></returns>
        public static Dictionary<string, List<string>> RegularList(List<string> originalText, string riu_id)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            Dictionary<string, List<string>> keyValues = new Dictionary<string, List<string>>();
            //new System.Threading.Tasks.TaskFactory().StartNew(() => {
            keyValues = Ruleobj.Dic_GetExtractList(originalText, riu_id);
            //}).Wait(25000);

            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            double times = timeSpan.TotalMilliseconds;
            WriteLog(string.Join(",", originalText), riu_id, times, "", false);
            return keyValues;
        }

        /// <summary>
        /// 执行正则
        /// </summary>
        /// <param name="riu_id">riuId</param>
        /// <param name="originalText">原文</param>
        /// <param name="Parameter">参数</param>
        /// <returns></returns>
        public static IList<string> ExtractList(string riu_id, string originalText, string Parameter)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            if (!string.IsNullOrEmpty(Parameter))
            {
                Parameter = Parameter.Replace("*", @"\*");
            }
            IList<string> listValue = new List<string>();
            // new System.Threading.Tasks.TaskFactory().StartNew(() => {
            listValue = Ruleobj.GetExtractList(riu_id, originalText, Parameter);
            // }).Wait(25000);

            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            double times = timeSpan.TotalMilliseconds;
            WriteLog(originalText, riu_id, times, Parameter, false);
            return listValue;
        }

        public static IList<string> ExtractList(string riu_id, string originalText)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            IList<string> listValue = new List<string>();
            //new System.Threading.Tasks.TaskFactory().StartNew(() => {
            listValue = Ruleobj.GetExtractList(riu_id, originalText);
            //}).Wait(25000);

            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            double times = timeSpan.TotalMilliseconds;
            WriteLog(originalText, riu_id, times, "", false);
            return listValue;
        }

        /// <summary>
        /// 正则超时记录（现场问题处理使用，暂时注释，不要删除）
        /// </summary>
        /// <param name="text">原文</param>
        /// <param name="code">正则编号</param>
        /// <param name="time">执行事件</param>
        /// <param name="paramter">参数</param>
        /// <param name="tagDateTime">是否记录</param>
        public static void WriteLog(string text, string code, double time, string paramter, bool tagDateTime)
        {
            //string regParam = !string.IsNullOrWhiteSpace(paramter) ? $"正则条件：{paramter}," : string.Empty;
            //string content = $"正则编号为【{code}】的正则执行时长{time}毫秒,{regParam}原文：{text}";
            //string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\log2\\reglog.txt";
            //string filefolder = AppDomain.CurrentDomain.BaseDirectory + "\\log2";
            //if (!Directory.Exists(filefolder))
            //    Directory.CreateDirectory(filefolder);
            //if (!File.Exists(filePath))
            //    File.Create(filePath).Close();
            //StreamWriter sw = new StreamWriter(filePath, true);
            //if (tagDateTime)
            //{
            //    sw.WriteLine("\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "----------------------------");
            //}
            //sw.WriteLine(content);
            //sw.WriteLine("\r\n");
            //sw.Close();
        }

        /// <summary>
        /// 正则超时记录（现场问题处理使用，暂时注释，不要删除）
        /// </summary>
        /// <param name="text">原文</param>
        /// <param name="code">正则编号</param>
        /// <param name="time">执行事件</param>
        /// <param name="paramter">参数</param>
        /// <param name="tagDateTime">是否记录</param>
        public static void WriteContentLog(string content)
        {
            //string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\log2\\reglog.txt";
            //string filefolder = AppDomain.CurrentDomain.BaseDirectory + "\\log2";
            //if (!Directory.Exists(filefolder))
            //    Directory.CreateDirectory(filefolder);
            //if (!File.Exists(filePath))
            //    File.Create(filePath).Close();
            //StreamWriter sw = new StreamWriter(filePath, true);
            //sw.WriteLine(content);
            //sw.WriteLine("\r\n");
            //sw.Close();
        }
    }
}
